package cn.e3mall.sso.service.impl;

import cn.e3mall.common.utils.E3Result;
import cn.e3mall.mapper.TbUserMapper;
import cn.e3mall.pojo.TbUser;
import cn.e3mall.pojo.TbUserExample;
import cn.e3mall.sso.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import sun.security.provider.MD5;

import java.util.Date;
import java.util.List;

@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private  TbUserMapper tbUserMapper;
    @Override
    public E3Result checkData(String params, Integer type) {

        //根据type生成查询条件
        TbUserExample tbUserExample = new TbUserExample();
        TbUserExample.Criteria criteria = tbUserExample.createCriteria();
        if(type==1){
            criteria.andUsernameEqualTo(params);
        }else if(type==2){
            criteria.andPhoneEqualTo(params);
        }else {
            return E3Result.build(400,"数据类型错误");
        }
        //执行查询
        List<TbUser> tbUsers = tbUserMapper.selectByExample(tbUserExample);
        //判断结果中是否包含数据
        if(tbUsers!=null&&tbUsers.size()==0){
            return E3Result.ok(true);
        }else {
            //返回结果
            return E3Result.ok(false);
        }

    }

    @Override
    public E3Result register(TbUser tbUser) {
        //数据有效性校验
        if(StringUtils.isEmpty(tbUser.getPassword())||StringUtils.isEmpty(tbUser.getUsername())
                ||StringUtils.isEmpty(tbUser.getPhone())){
            return E3Result.build(400,"数据不完整");
        }
        E3Result e3Result = checkData(tbUser.getUsername(), 1);
        if(e3Result.getStatus()==400){
            return E3Result.build(400,"用户名被占用");
        }
        E3Result e3Result2 = checkData(tbUser.getPhone(), 2);
        if(e3Result2.getStatus()==400){
            return E3Result.build(400,"手机号被注册");
        }
        //补全信息
        tbUser.setCreated(new Date());
        tbUser.setUpdated(new Date());
        //mad5加密
        tbUser.setPassword(DigestUtils.md5DigestAsHex(tbUser.getPassword().getBytes()));
        //插入数据库
        tbUserMapper.insert(tbUser);
        return E3Result.ok();
    }
}
